/**
 * 
 */
package cc.comac.mom.service.impl;

import java.math.BigDecimal;
import java.util.*;

import cc.comac.mom.datahandlers.entity.EquipPartBorrowDemandDataHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cc.comac.mom.api.EquipPartBorrowService;
import cc.comac.mom.bean.EquipPartBorrow;
import cc.comac.mom.bean.EquipPartBorrowBean;
import cc.comac.mom.bean.EquipPartBorrowDetail;
import cc.comac.mom.bean.EquipPartBorrowDetailBean;
import cc.comac.mom.bean.ResultDev;
import cc.comac.mom.dao.entity.EquipPartBorrowDemandDao;
import cc.comac.mom.datahandlers.entity.EquipPartBorrowDataHandler;
import cc.comac.mom.datahandlers.entity.EquipPartBorrowDetailDataHandler;
import cc.comac.mom.datahandlers.entity.EquipWarehouseStockDataHandler;
import cc.comac.mom.entity.EquipPartBorrowDemandEntity;
import cc.comac.mom.entity.EquipPartBorrowDetailEntity;
import cc.comac.mom.entity.EquipPartBorrowEntity;
import cc.comac.mom.entity.EquipWarehouseStockEntity;
import cc.comac.mom.util.BaseEntityDataUtil;
import cc.comac.mom.util.IModificationFlags;
import cc.comac.mom.util.MomConstants;
import cc.comac.mom.util.ResultBean;

/**
* @Description: 
* @author: fyt 
 * @param <E>
* @date: 2020年7月16日下午9:36:42
*/
@Service
@RestController
@Transactional
public class EquipPartBorrowServiceImpl implements EquipPartBorrowService{

	@Autowired
	private EquipPartBorrowDataHandler equipPartBorrowDataHandler;
	@Autowired
	private EquipPartBorrowDetailDataHandler equipPartBorrowDetailDataHandler;
	@Autowired
	private EquipWarehouseStockDataHandler equipWarehouseStockDataHandler;
	@Autowired
	private EquipPartBorrowDemandDao equipPartBorrowDemandDao;
	@Autowired
	private EquipPartBorrowDemandDataHandler equipPartBorrowDemandDataHandler;
	
	@Autowired
	private BaseEntityDataUtil baseEntityDataUtil;
	@Override
	public ResultBean save(@RequestBody EquipPartBorrow obj) {
		ResultBean resultBean = new ResultBean(true);
		if(obj == null) {
			resultBean.setSuccess(false);
			resultBean.setMessage("数据为空");
			return resultBean;
		}
		List<EquipPartBorrowDetail> listItem = obj.getListItem();
		if(listItem == null || listItem.size()<1) {
			resultBean.setSuccess(false);
			resultBean.setMessage("数据为空");
			return resultBean;
		}
		//保存主表信息
		ResultBean resultBean2 = equipPartBorrowDataHandler.save(obj);
		if(!resultBean2.success) {
			return resultBean2;
		}
		long borrowId =Long.valueOf(resultBean2.getMessage());
		for(EquipPartBorrowDetail item:listItem) {
			item.getInnerData().setBorrowId(borrowId);
		}
		//保存子表信息
		ResultBean saveBatch = equipPartBorrowDetailDataHandler.saveBatch(listItem);
		if(!saveBatch.success) {
			throw new RuntimeException("保存失败"+saveBatch.getMessage());
		}
		//扣除备件主数据数量
//		for(EquipPartBorrowDetail item :listItem) {
//			boolean updateCountById = equipSparePartMasterDataDataHandler.updateCountById(item.getInnerData().getSparePartId(), item.getInnerData().getBorrowQty().doubleValue());
//			if(!updateCountById) {
//				throw new RuntimeException("主数据库存扣减失败");
//			}
//			
//		}
		// 判断数据是否是从领用需求过来的，如果是，保存时更新领用需求数据
		if (obj.isDemand()) {
			// 查询对应的领用需求数据
			QueryWrapper<EquipPartBorrowDemandEntity> queryWrapper = new QueryWrapper<EquipPartBorrowDemandEntity>();
			queryWrapper.eq("row_status", 1);
			queryWrapper.eq("borrow_demand_status", 1);
			queryWrapper.in("borrow_demand_id", obj.getDemandIds());
			List<EquipPartBorrowDemandEntity> selectList = equipPartBorrowDemandDao.selectList(queryWrapper);
			if (selectList.size() > 0) {
				// 通过计算判断领用需求创建备件领用单时是否将所有的领用请求数量全部扣减完成，并计算出对应数据更新领用需求表状态
				for (EquipPartBorrowDemandEntity equipPartBorrowDemandEntity : selectList) {
					baseEntityDataUtil.updateBaseEntityData(equipPartBorrowDemandEntity);
					for (EquipPartBorrowDetail equipPartBorrowDetail : listItem) {
						EquipPartBorrowDetailEntity innerData = equipPartBorrowDetail.getInnerData();
						if (innerData.getSparePartId() == equipPartBorrowDemandEntity.getSparePartId()) {
							BigDecimal add = equipPartBorrowDemandEntity.getBorrowQuantity().add(innerData.getBorrowQty());
							if (add.compareTo(equipPartBorrowDemandEntity.getApplyQuantity()) != -1 ) {
								equipPartBorrowDemandEntity.setBorrowQuantity(equipPartBorrowDemandEntity.getBorrowQuantity());
								equipPartBorrowDemandEntity.setRemainingQuantity(new BigDecimal(0));
								equipPartBorrowDemandEntity.setBorrowDemandStatus("0");
							} else {
								equipPartBorrowDemandEntity.setBorrowQuantity(equipPartBorrowDemandEntity.getBorrowQuantity().add(innerData.getBorrowQty()));
								equipPartBorrowDemandEntity.setRemainingQuantity(equipPartBorrowDemandEntity.getApplyQuantity().subtract(equipPartBorrowDemandEntity.getBorrowQuantity()));
							}
							equipPartBorrowDemandDao.updateById(equipPartBorrowDemandEntity);
							break;
						}
					}
					
				}
			}
		}
		return resultBean;
	}

	@Override
	public ResultDev selectByFields(@RequestBody EquipPartBorrowBean obj) {
		// TODO Auto-generated method stub
		return equipPartBorrowDataHandler.selectByFields(obj);
	}

	@Override
	public ResultDev selectBorrowDetailByFields(@RequestBody EquipPartBorrowDetailBean obj) {
		// TODO Auto-generated method stub
		return equipPartBorrowDetailDataHandler.selectByFields(obj);
	}
	/**
	 * 领用单确认，库存扣除
	 */
	@Override
	public ResultBean borrowConfig(@RequestBody List<Long> ids) {
		ResultBean resultBean = new ResultBean(true);
		Collection<EquipPartBorrowEntity> listByIds = equipPartBorrowDataHandler.listByIds(ids);
		if(listByIds != null && listByIds.size()>0) {
			for(EquipPartBorrowEntity item :listByIds) {
				if(!MomConstants.EQUIP_PART_BORROW_STATUS_UNCONFIRM.equals(item.getBorrowConfirm())) {
					resultBean.setSuccess(false);
					resultBean.setMessage(item.getBorrowOrderNumber()+"该单号已经确认不能再次确认");
					return resultBean;
				}
			}
		}
		ResultBean resultBean2 = equipPartBorrowDataHandler.borrowConfig(ids);
		if(!resultBean2.success) {
			return resultBean2;
		}
		QueryWrapper<EquipPartBorrowDetailEntity> queryWrapper = new QueryWrapper<EquipPartBorrowDetailEntity>();
		queryWrapper.eq("row_status",1);
		queryWrapper.in("borrow_id", ids);
		List<EquipPartBorrowDetailEntity> listBorrowDetailEntity = equipPartBorrowDetailDataHandler.list(queryWrapper);
		if(listBorrowDetailEntity != null && listBorrowDetailEntity.size()>0) {
			ArrayList<EquipWarehouseStockEntity> listWarehouseStockEntity = new ArrayList<EquipWarehouseStockEntity>();
			Map<Long,BigDecimal> map=new HashMap<>();
			for(EquipPartBorrowDetailEntity item :listBorrowDetailEntity) {
				EquipWarehouseStockEntity warehouseStockEntity = equipWarehouseStockDataHandler.getById(item.getWarehouseId());
				if(warehouseStockEntity == null) {
					throw new RuntimeException("库存信息不存在！");
				}
				//领用数量
				BigDecimal borrowQty = item.getBorrowQty();
				if(map.containsKey(item.getSparePartId())){
					map.put(item.getSparePartId(),map.get(item.getSparePartId()).add(borrowQty));
				}else{
					map.put(item.getSparePartId(),borrowQty);
				}
				//库存数量
				BigDecimal inventoryQty = new BigDecimal(warehouseStockEntity.getQuantity());
				if(borrowQty.compareTo(inventoryQty)>0) {
					throw new RuntimeException("库存不足！");
				}
				warehouseStockEntity.setQuantity(inventoryQty.subtract(borrowQty).doubleValue());
				listWarehouseStockEntity.add(warehouseStockEntity);
			}
			boolean updateBatchById = equipWarehouseStockDataHandler.updateBatchById(listWarehouseStockEntity);
			//修改领用数据
			QueryWrapper<EquipPartBorrowDemandEntity> borrow = new QueryWrapper<EquipPartBorrowDemandEntity>();
			borrow.eq("row_status",1);
			borrow.eq("relation_number", listBorrowDetailEntity.get(0).getRelationNumber());
			borrow.eq("borrow_style",listBorrowDetailEntity.get(0).getBorrowStyle());
			List<EquipPartBorrowDemandEntity> demandList = equipPartBorrowDemandDataHandler.list(borrow);
			boolean flag=true;
			if(demandList!=null&&demandList.size()>0){
				for(EquipPartBorrowDemandEntity d:demandList ){
					if(d.getBorrowQuantity()==null){
						d.setBorrowQuantity(new BigDecimal(0));
					}
					if(map.containsKey(d.getSparePartId())&&d.getApplyQuantity().compareTo(d.getBorrowQuantity())==1){
						BigDecimal tb=d.getApplyQuantity().subtract(d.getBorrowQuantity());
						if(tb.compareTo(map.get(d.getSparePartId()))!=1){
							d.setBorrowQuantity(d.getBorrowQuantity().add(tb));
							map.put(d.getSparePartId(),map.get(d.getSparePartId()).subtract(tb));
						}else{
							d.setBorrowQuantity(d.getBorrowQuantity().add(map.get(d.getSparePartId())));
							map.put(d.getSparePartId(),new BigDecimal(0));
						}
					}
				}
				for(EquipPartBorrowDemandEntity d:demandList ){
					if(map.containsKey(d.getSparePartId())&&map.get(d.getSparePartId()).compareTo(new BigDecimal(0))!=0){
						throw new RuntimeException("已经超过申请数量");
					}

				}
				flag=equipPartBorrowDemandDataHandler.updateBatchById(demandList);
			}

			if(!updateBatchById||!flag) {
				throw new RuntimeException("库存扣减失败！");
			}
		}
		return resultBean;
	}

	@Override
	public ResultBean deleteBatch(@RequestBody List<EquipPartBorrow> list) {
		ResultBean resultBean = new ResultBean(true);
		ResultBean deleteBatch = equipPartBorrowDataHandler.deleteBatch(list);
		if(!deleteBatch.success) {
			return deleteBatch;
		}
		ArrayList<Long> listIds = new ArrayList<Long>();
		for(EquipPartBorrow item:list) {
			listIds.add(item.getInnerData().getId());
		}
		List<EquipPartBorrowDetail> listEquipPartBorrowDetail = equipPartBorrowDetailDataHandler.getBorrowIds(listIds);
		if(listEquipPartBorrowDetail != null && listEquipPartBorrowDetail.size()>0) {
			ResultBean deleteBatch2 = equipPartBorrowDetailDataHandler.deleteBatch(listEquipPartBorrowDetail);
			if(!deleteBatch2.success) {
				new RuntimeException(deleteBatch2.getMessage());
			}
		}
		return resultBean;
	}

	@Override
	public ResultBean update(@RequestBody EquipPartBorrow obj) {
		ResultBean resultBean = new ResultBean(true);
		ResultBean resultBean2 = equipPartBorrowDataHandler.update(obj);
		if(!resultBean2.success) {
			return resultBean2;
		}
		List<EquipPartBorrowDetail> listItem = obj.getListItem();
		ArrayList<EquipPartBorrowDetail> listNew = new ArrayList<EquipPartBorrowDetail>();
		ArrayList<EquipPartBorrowDetail> listUpdate = new ArrayList<EquipPartBorrowDetail>();
		if(listItem != null && listItem.size()>0) {
			for(EquipPartBorrowDetail item :listItem) {
				if(item.getModificationFlag() == IModificationFlags.NEW) {
					listNew.add(item);
				}else if(item.getModificationFlag() == IModificationFlags.MODIFIED) {
					listUpdate.add(item);
				}
			}
		}
		if(listNew != null && listNew.size()>0) {
			ResultBean saveBatch = equipPartBorrowDetailDataHandler.saveBatch(listNew);
			if(!saveBatch.success) {
				throw new RuntimeException(saveBatch.getMessage());
			}
		}
		if(listUpdate != null && listUpdate.size()>0) {
			ResultBean updateBatch = equipPartBorrowDetailDataHandler.updateBatch(listUpdate);
			if(!updateBatch.success) {
				throw new RuntimeException(updateBatch.getMessage());
			}
		}
		return resultBean;
	}

	@Override
	public ResultBean deleteBatchBorrowDetail(@RequestBody List<EquipPartBorrowDetail> list) {
		// TODO Auto-generated method stub
		return equipPartBorrowDetailDataHandler.deleteBatch(list);
	}
}
